package net.wofly.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期相关计算辅助类<br/>
 * Copyright (c) 2014 , 北京可思云海科技有限公司<br/>
 * 2014-10-30 上午10:29:35
 * 
 * @author gyj@kscloud.com
 * @version V1.0
 */
@Slf4j
public class DateUtil {

	public static final String FORMAT_STR = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 计算年龄
	 * 
	 * @param birthDay
	 * @return
	 * @throws Exception
	 */
	public static Integer getAge(Date birthDay) {
		Calendar cal = Calendar.getInstance();

		if (cal.before(birthDay)) {
			throw new IllegalArgumentException("出生日期不能在当前日期之后!");
		}

		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

		cal.setTime(birthDay);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH);
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

		int age = yearNow - yearBirth;

		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				if (dayOfMonthNow < dayOfMonthBirth) {
					age--;
				}
			} else {
				age--;
			}
		}

		return age;
	}

//	public static void main(String[] args) {
//
//	}

	/**
	 * 处理开始时间
	 * 当天时间的0时0分0秒
	 * 
	 * @param start
	 * @return
	 */
	public static Date processStartTime(Date start) {
		Calendar c = Calendar.getInstance();
		c.setTime(start);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();
	}

	/**
	 * 处理结束时间
	 * 当天时间的23时59分59秒
	 * 
	 * @param endTime
	 * @return
	 */
	public static Date processEndTime(Date endTime) {
		Calendar c = Calendar.getInstance();
		c.setTime(endTime);
		c.set(Calendar.HOUR_OF_DAY, 23);
		c.set(Calendar.MINUTE, 59);
		c.set(Calendar.SECOND, 59);
		return c.getTime();
	}

	/**
	 * 解析日期
	 * 格式"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm","yyyy-MM-dd HH","yyyy-MM-dd"
	 * 
	 * @param dateStr
	 * @return Date
	 */
	public static Date parseDate(String dateStr) {
		String[] dateFormatStr = new String[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH", "yyyy-MM-dd" };
		if (!StringUtils.isEmpty(dateStr)) {
			dateStr = dateStr.trim();
			for (int i = 0; i < dateFormatStr.length; i++) {
				if (dateStr.length() >= dateFormatStr[i].length()) {
					try {
						return DateUtils.parseDate(dateStr, dateFormatStr[i]);
					} catch (Exception e) {
						log.error(e.getMessage());
						return null;
					}
				}
			}
		}
		return null;
	}

	/**
	 * 通过睡眠时间获取所属日睡眠记录的执行日期
	 * 
	 * @param date
	 * @return Date
	 */
	public static Date getSleepDay(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		if (c.get(Calendar.HOUR_OF_DAY) < 6) {
			return processStartTime(DateUtils.addDays(date, -1));
		} else {
			return processStartTime(date);
		}
	}
	
	/**
	 * 获取冒号分割的时间字符串
	 * 
	 * @param duration
	 *            时长（单位：秒）
	 * @param format
	 *            时间格式
	 * @return String 格式化后的时间字符串
	 */
	public static String getTimeStrWithColon(Integer duration, String format) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.add(Calendar.SECOND, duration);

		if (GeneralHelper.isTrimStrEmpty(format)) {
			if (c.get(Calendar.HOUR_OF_DAY) > 0) {
				format = "HH:mm:ss";
			} else if (c.get(Calendar.MINUTE) > 0) {
				format = "mm:ss";
			} else {
				format = "ss";
			}
		}
		return GeneralHelper.date2Str(c.getTime(), format);
	}

	/**
	 * 获取汉字分割的时间字符串
	 * 
	 * @param duration
	 *            时长（单位：秒）
	 * @param format
	 *            时间格式
	 * @return String 格式化后的时间字符串
	 */
	public static String getTimeStrWithChinese(Integer duration, String format) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.add(Calendar.SECOND, duration);

		if (GeneralHelper.isTrimStrEmpty(format)) {
			if (c.get(Calendar.HOUR_OF_DAY) > 0) {
				format = "HH小时mm分ss秒";
			} else if (c.get(Calendar.MINUTE) > 0) {
				format = "mm分ss秒";
			} else {
				format = "ss秒";
			}
		}
		return GeneralHelper.date2Str(c.getTime(), format);
	}
	
	/**
	 * 格式化输出日期
	 * @param date
	 * @return	Date    返回类型
	 */
	public static Date getForMatDate(Date date){
		return getForMatDate(date,FORMAT_STR);
	}
	/**
	 * 格式化输出日期
	 * @param date
	 * @return	Date    返回类型
	 */
	public static Date getForMatDate(Date date,String pattern){
		if(StringUtils.isEmpty(pattern)){
			pattern=FORMAT_STR;
		}
		SimpleDateFormat fmat= new SimpleDateFormat(pattern);
		try {
			return fmat.parse(fmat.format(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return new Date();
	}
	
	public static String getDateToString(Date date,String pattern){
		if(StringUtils.isEmpty(pattern)){
			pattern=FORMAT_STR;
		}
		SimpleDateFormat fmat= new SimpleDateFormat(pattern);
		return fmat.format(date);
	}
	/**
	 * 给定事前是否在服务器规定时间范围内
	 * @param preTo
	 * @return	boolean    返回类型
	 */
	public static boolean isValid(Date preTo){
		if(preTo==null){
			return false;
		}
		Date now = new Date();
		long first=now.getTime()-24*60*60*1000;
		long second=preTo.getTime();
		long third=now.getTime()+20*60*1000;
		if(second>=first&&second<=third){
			return true;
		}
		return false;
	}
	/**
	 * 
	 * @Description: 比较睡眠日期是否合法
	 * @param preTo
	 * @return	boolean    返回类型
	 */
	public static boolean isValidSleep(Date endTime){
		if(endTime==null){
			return false;
		}
		Date now = new Date();
		long first=now.getTime()-48*60*60*1000;
		long second=endTime.getTime();
		long third=now.getTime()+24*60*60*1000;
		if(second>=first&&second<=third){
			return true;
		}
		return false;
	}
	
	public static Date getAddDate(Date now,int day){
		Calendar cal = Calendar.getInstance();
		cal.setTime(now);
		cal.add(Calendar.DATE, day);
		return cal.getTime();
	}
}
